/*
Copyright (c) 2007 Emmanuel Bonnet, blog.emmanuelbonnet.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package wiiless.wiiless
{
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.events.EventDispatcher;
	import flash.display.DisplayObject;
	import wiiless.events.WiilessEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.display.Stage;
	import wiiless.core.ACursor;
	import wiiless.utils.ColorMatrix;
	import flash.filters.ColorMatrixFilter;
	import wiiless.utils.UColor;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	public class Wiiless extends EventDispatcher
	{
		/**
		 * Id d'incrémentation pour chaque objet créé
		 */
		public static var idIncr:int = 0;
		
		/**
		 * Id de la Wiiless
		 */
		private var _iId:int;
		
		/**
		 * stage
		 */
		private var _stage:Stage;
		
		/**
		 * delais de detection
		 */
		private var _iDelay:int;
		
		/**
		 * précision des passes
		 */
		private var _iPrecision:int;
		
		/**
		 * 
		 */
		private var _iNotch:int;
		
		/**
		 * taille de la zone
		 */
		private var _oSize:Object;
		
		/**
		 * plage de couleur
		 */
		private var _oRGB:Object;
		
		/**
		 * container de la Wiiless
		 */
		private var _container:DisplayObject;
		
		/**
		 * video
		 */
		private var _video:Video;
		
		/**
		 * bitmap de detection
		 */
		private var _bmp:BitmapData;
		
		/**
		 * curseur attribué a la Wiiless
		 */
		private var _cursor:ACursor;
		
		/**
		 * filtre sur le bitmap
		 */
		private var _cm:ColorMatrixFilter;
		
		/**
		 * point courant
		 */
		private var _currentPoint:Object;
		
		/**
		 * Si la touche est enfoncé
		 */
		private var _isPressed:Boolean;
		
		/**
		 * timer d'update des detections
		 */
		private var _timer:Timer;
		
		/**
		 * Constructeur
		 */
		function Wiiless()
		{
			_iId = ++Wiiless.idIncr;
			_iDelay = 100;
			_iPrecision = 10;
			_iNotch = 15;
			_oSize = {width:550, height:400};
			_oRGB = new Object();
			_currentPoint = {x:0, y:0, z:0};
		}
		
		/**
		 * init
		 */
		private function _init():void
		{
			var camera:Camera = Camera.getCamera();
			_video = new Video(_oSize.width, _oSize.height);
			_video.attachCamera(camera);
			
			_bmp = new BitmapData(_oSize.width, _oSize.height, false, 0xFFFFFF);
			var mat:ColorMatrix = new ColorMatrix();
			mat.adjustSaturation(3);
			_cm = new ColorMatrixFilter(mat.matrix);
			
			_container.addEventListener(Event.ENTER_FRAME, _onEnterFrame);
		}
		
		/**
		 * Connexion de la wiiless
		 * 
		 * @param	pContainer		Container de la wiiless
		 * @param	pBmp			Bitmap source de la vidéo si plusieurs wiiless
		 */
		public function connect(pContainer:DisplayObject, pBmp:BitmapData=null):void
		{
			if(pContainer) _container = pContainer;
			
			if(!_oSize || !_oRGB)
				throw new Error("Hé Oh !Tu n'oublies rien ?");
				
			if(pBmp) _bmp = pBmp;
			else _init();
			
			_stage = pContainer.stage;
			
			_timer = new Timer(_iDelay);
			_timer.addEventListener("timer", _checkPoint);
            _timer.start();
			
			_stage.addEventListener(MouseEvent.MOUSE_DOWN, _mouseDown);
			_stage.addEventListener(MouseEvent.MOUSE_UP, _mouseUp);
			_stage.addEventListener(MouseEvent.MOUSE_WHEEL, _mouseWheel);	
			
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.CONNECT);
			ev.id = _iId;
			dispatchEvent(ev);
		}
		
		/**
		 * Déconnexion de la wiiless
		 */
		public function disconnect():void
		{
			_timer.stop();
			
			_container.removeEventListener(Event.ENTER_FRAME, _onEnterFrame);
			
			_stage.removeEventListener(MouseEvent.MOUSE_DOWN, _mouseDown);
			_stage.removeEventListener(MouseEvent.MOUSE_UP, _mouseUp);	
			_stage.removeEventListener(MouseEvent.MOUSE_WHEEL, _mouseWheel);	
			
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.DISCONNECT);
			ev.id = _iId;
			dispatchEvent(ev);
		}
		
		/**
		 * 
		 */
		private function _mouseDown(e:MouseEvent):void
		{	
			_isPressed = true;
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.PRESS);
			ev.id = _iId;
			ev.point = _currentPoint;
			dispatchEvent(ev);
		}
		
		/**
		 * 
		 */
		private function _mouseUp(e:MouseEvent):void
		{
			_isPressed = false;
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.RELEASE);
			ev.id = _iId;
			ev.point = _currentPoint;
			dispatchEvent(ev);
		}
		
		/**
		 * 
		 */
		private function _mouseWheel(e:MouseEvent):void
		{
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.WHEEL);
			ev.id = _iId;
			ev.point = _currentPoint;
			dispatchEvent(ev);
		}
		
		/**
		 * 
		 */
		private function _onEnterFrame(e:Event):void
		{
			_bmp.draw(_video);
			_bmp.applyFilter(_bmp, _bmp.rect, new Point(0,0), _cm);
		}
		
		/**
		 * Détection du point
		 * 
		 * @param 	e		Evenement Timer
		 */
		private function _checkPoint(e:TimerEvent):void
		{
			var b:Boolean = false;
			
			var p:int = _iPrecision;
			
			var aPts:Array = new Array();
			var x:int = 0;
			while(x < _oSize.width)
			{
				var y:int = 0;
				while(y < _oSize.height)
				{
					var color:Object = UColor.hexToRGB(_bmp.getPixel(x, y));
					if(color.r>_oRGB.min.r && color.r<_oRGB.max.r 
					&& color.g>_oRGB.min.g && color.g<_oRGB.max.g
					&& color.b>_oRGB.min.b && color.b<_oRGB.max.b)
					{
						aPts.push(new Point(x, y));
					}
					y += p;
				}
				x += p;
			}
			var ev:WiilessEvent = new WiilessEvent(WiilessEvent.MOVE);
			if(aPts.length>0) 
			{
				var xTot:Number = 0;
				var yTot:Number = 0;
				var nPts:int = aPts.length;
				var i:int = -1;
				while(++i < nPts)
				{
					xTot += aPts[i].x;
					yTot += aPts[i].y;
				}
				var newPoint:Object = {x:Math.floor(xTot/nPts), y:Math.floor(yTot/nPts), z:Math.ceil(nPts/10)*10/_iPrecision};
				if(Math.sqrt(Math.pow(newPoint.x-_currentPoint.x, 2)+Math.pow(newPoint.y-_currentPoint.y, 2))>_iNotch)
				{
					_currentPoint = newPoint;
					ev.id = _iId;
					ev.point = _currentPoint;
					dispatchEvent(ev);
				}
			}
			else {
				ev.id = _iId;
				ev.point = null
				dispatchEvent(ev);
			}
			
		}
		
		/**
		 * Définition de la zone de detection
		 * 
		 * @param	pWidth		Largeur
		 * @param	pHeight		Hauteur
		 */
		public function setZone(pWidth:int, pHeight:int):void
		{
			_oSize.width = pWidth;
			_oSize.height = pHeight;
		}
		
		/**
		 * Couleur RGB à detecter
		 * 
		 * @param	pRed		Rouge
		 * @param	pGreen		Vert
		 * @param	pBlue		Bleu
		 * @param	pSpace		Espace de détection
		 */
		public function setRGB(pRed:Number, pGreen:Number, pBlue:Number, pSpace:Number=100):void
		{
			if(!isNaN(pRed) && !isNaN(pGreen) && !isNaN(pBlue))
			{
				_oRGB.min = {r:pRed-pSpace>0 ? pRed-pSpace : 0,
							 g:pGreen-pSpace>0 ? pGreen-pSpace : 0,
							 b:pBlue-pSpace>0 ? pBlue-pSpace : 0};
				_oRGB.max = {r:pRed+pSpace<255 ? pRed+pSpace : 255,
							 g:pGreen+pSpace<255 ? pGreen+pSpace : 255,
							 b:pBlue+pSpace<255 ? pBlue+pSpace : 255};
			}
				
		}
		
		/**
		 * Couleur RGB minimum à detecter
		 * 
		 * @param	pRed		Rouge
		 * @param	pGreen		Vert
		 * @param	pBlue		Bleu
		 */
		public function setMinRGB(pRed:Number, pGreen:Number, pBlue:Number):void
		{
			if(!isNaN(pRed) && !isNaN(pGreen) && !isNaN(pBlue))
				_oRGB.min = {r:pRed, g:pGreen, b:pBlue};
		}

		/**
		 * Couleur RGB maximum à detecter
		 * 
		 * @param	pRed		Rouge
		 * @param	pGreen		Vert
		 * @param	pBlue		Bleu
		 */
		public function setMaxRGB(pRed:Number, pGreen:Number, pBlue:Number):void
		{
			if(!isNaN(pRed) && !isNaN(pGreen) && !isNaN(pBlue))
				_oRGB.max = {r:pRed, g:pGreen, b:pBlue};
		}
		
		/**
		 * Retourne la couleur minimum à detecter
		 */
		public function getMinRGB():Object
		{
			return _oRGB.min;
		}
		
		/**
		 * Retourne la couleur maximum à detecter
		 */
		public function getMaxRGB():Object
		{
			return _oRGB.max;
		}
		
		// ------------------------ get/setter


		/**
		 * Retourne le point courant de la wiiless
		 */
		public function get currentPoint():Object
		{
			return _currentPoint;
		}
		
		/**
		 * Id de la wiiless
		 */
		public function get id():int
		{
			return _iId;
		}
		
		public function set id(pId:int):void
		{
			_iId = pId;
		}
		
		/**
		 * Delay
		 */
		public function get delay():int
		{
			return _iDelay;
		}
		
		public function set delay(pDelay:int):void
		{
			_iDelay = pDelay;
		}
		
		/**
		 * Container
		 */
		public function get container():DisplayObject
		{
			return _container;
		}
		
		public function set container(pContainer:DisplayObject):void
		{
			_container = pContainer;
		}
		
		/**
		 * ZoneHeight
		 */
		public function get zoneHeight():int
		{
			return _oSize.height;
		}
		
		public function set zoneHeight(pHeight:int):void
		{
			_oSize.height = pHeight;
		}
		
		/**
		 * ZoneWidth
		 */
		public function get zoneWidth():int
		{
			return _oSize.width;
		}
		
		public function set zoneWidth(pWidth:int):void
		{
			_oSize.width = pWidth;
		}
		
		/**
		 * Precision
		 */
		public function get precision():int
		{
			return _iPrecision;
		}
		
		public function set precision(pPrecision:int):void
		{
			_iPrecision = pPrecision;
		}
		
		/**
		 * Notch
		 */
		public function get notch():int
		{
			return _iNotch;
		}
		
		public function set notch(pNotch:int):void
		{
			_iNotch = pNotch;
		}
		
		/**
		 * Curseur
		 */
		public function get cursor():ACursor
		{
			return _cursor;
		}
		
		public function set cursor(pCursor:ACursor):void
		{
			_cursor = pCursor;
		}
		
		/**
		 * Bitmap
		 */
		public function get bmp():BitmapData
		{
			return _bmp;
		}
		
		public function set bmp(pBitmap:BitmapData):void
		{
			_bmp = pBitmap;
		}
		
		/**
		 * Vidéo
		 */
		public function get video():Video
		{
			return _video;
		}
		
		/**
		 * Si pression
		 */
		public function get isPressed():Boolean
		{
			return _isPressed;
		}
		
	}
}